package com.itheima.pxgl.service.impl;

import com.itheima.pxgl.common.context.BaseContext;
import com.itheima.pxgl.common.exception.novel.NovelExistsException;
import com.itheima.pxgl.entity.pojo.Novel;
import com.itheima.pxgl.entity.pojo.ApUser;
import com.itheima.pxgl.entity.vo.NovelVo;
import com.itheima.pxgl.mapper.ApUserMapper;
import com.itheima.pxgl.mapper.CategoryMapper;
import com.itheima.pxgl.mapper.NovelMapper;
import com.itheima.pxgl.service.INovelService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 九尾
 * @since 2024-05-19
 */
@Service
@Slf4j
public class NovelServiceImpl extends ServiceImpl<NovelMapper, Novel> implements INovelService {
@Autowired
private  NovelMapper novelMapper;
@Autowired
private CategoryMapper categoryMapper;
@Autowired
private ApUserMapper apUserMapper;
    @Override
    public List<Novel> getNovelListByid() {
        Long currentId = BaseContext.getCurrentId();
        List<Novel> novelList = novelMapper.getNovelByUserId(currentId);
        log.info("当前novelIds为{}",novelList);

        return novelList;
    }

    /**
     * 创建小说
     * @param novelVo
     */
    @Override
    public void insertNovel(NovelVo novelVo) {
//        判断前端传送过来的novelVo是否合法
        List<String> novelNames =  novelMapper.listName();
        log.info("{}",novelNames);
//        定义实体novel
        for (String novelName : novelNames) {
            if(novelVo.getTitle().equals( novelName)){
                throw new NovelExistsException();
            }
        }
        Novel novel = new Novel();
        BeanUtils.copyProperties(novelVo,novel);
        Integer categoryId = categoryMapper.getIdByName(novelVo.getCategoryName());

        novel.setNovelId((int) System.currentTimeMillis());
        novel.setUserId(Math.toIntExact(BaseContext.getCurrentId()));
        ApUser apUser = apUserMapper.selectById(novel.getUserId());
        novel.setAuthor(apUser.getUsername());
        novel.setCategoryId(categoryId);
        novel.setCreateTime(LocalDateTime.now());
        log.info("novel为{}",novel);
        novelMapper.insert(novel);
    }
}
